<template>
  <div>
    <div class="mb-3">
      <el-form class="query-form" :inline="true" :model="params">
        <el-form-item label="项目名称查询">
          <el-input v-model="params.customer_name" placeholder="项目名称查询" clearable>
            <i class="el-icon-search el-input__icon" slot="suffix" @click="getData()"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="资产名称查询">
          <el-input v-model="params.product_name" placeholder="资产名称查询" clearable>
            <i class="el-icon-search el-input__icon" slot="suffix" @click="getData()"></i>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="dialogImportVisible = true">
            <i class="fa fa-fw fa-upload"></i>
            导入资产信息
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column align="center" label="贷款主体证件号">
          <template slot-scope="scope">
            {{ scope.row.lender_idcard }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="项目名" prop="customer_name">
          <template slot-scope="scope">
            {{ scope.row.customer_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="资产名" prop="assets_name">
          <template slot-scope="scope">
            {{ scope.row.assets_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型">
          <template slot-scope="scope">
            {{ enumAssetsType[scope.row.assets_type] || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="所在位置" prop="address_detail">
          <template slot-scope="scope">
            {{ scope.row.address_detail || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="购置时间">
          <template slot-scope="scope">
            <span v-if="scope.row.purchase_date">
              {{ $utils.dateFormat(scope.row.purchase_date, 'yyyy') }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" prop="assets_amount">
          <template slot-scope="scope">
            {{ scope.row.assets_amount || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位" prop="assets_unit">
          <template slot-scope="scope">
            {{ scope.row.assets_unit || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="价值（万元）" prop="assets_value">
          <template slot-scope="scope">
            {{ scope.row.assets_value || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="权证情况" prop="own_sit">
          <template slot-scope="scope">{{ enumOwnSit[scope.row.own_sit] || '-' }}</template>
        </el-table-column>
        <el-table-column align="center" label="是否抵押">
          <template slot-scope="scope">{{ enumIsMortgage[scope.row.is_mortgage] || '-' }}</template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark">
          <template slot-scope="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </el-table-column>
        <!--<el-table-column-->
        <!--align="center"-->
        <!--label="操作"-->
        <!--width="100px">-->
        <!--<template-->
        <!--slot-scope="scope">-->
        <!--<el-button v-if="scope.row.customer_related_id === 'relatedId'" class="py-0 px-2"-->
        <!--type="text"-->
        <!--@click="eventuate(scope.row)">-->
        <!--归集-->
        <!--</el-button>-->
        <!--<span v-else>已归集</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
      </el-table>
      <div class="query-pagination">
        <el-pagination
          @current-change="getData"
          :current-page.sync="params.index"
          :page-size="params.size"
          layout="total, prev, pager, next, jumper"
          :total="totalCount"
        ></el-pagination>
      </div>
    </loading-wrap>

    <el-dialog
      append-to-body
      top="30px"
      width="800px"
      :close-on-click-modal="false"
      :before-close="beforeClose"
      title=""
      :visible.sync="editVisible"
    >
      <form novalidate class="my-3" ref="form" :class="{ 'was-validated': wasValidated }">
        <div class="form-group row">
          <label class="col-sm-2 col-form-label" for="assets_name">
            <span class="text-danger mr-1">*</span>
            <span>资产名</span>
          </label>
          <div class="col-sm-10">
            <input
              v-model="editData.assets_name"
              class="form-control form-control-ml"
              id="assets_name"
              placeholder="请输入资产名"
              required
              type="text"
            />
            <div class="invalid-feedback">请输入资产名</div>
          </div>
        </div>

        <fieldset class="form-group">
          <div class="row">
            <legend class="col-form-label col-sm-2 pt-0">
              <span class="text-danger mr-1">*</span>
              <span>类型</span>
            </legend>
            <div class="col-sm-10">
              <div
                v-for="(value, rKey, index) in enumAssetsType"
                class="form-check form-check-inline"
                :key="index"
              >
                <input
                  v-model="editData.assets_type"
                  class="form-check-input"
                  :id="`assets_type${index}`"
                  name="assets_type"
                  type="radio"
                  required
                  :value="rKey"
                />
                <label class="form-check-label" :for="`assets_type${index}`">{{ value }}</label>
              </div>
            </div>
          </div>
        </fieldset>

        <div class="form-group row">
          <label class="col-sm-2 col-form-label">所在地区</label>
          <div class="col-sm-10 form-control-ml">
            <select-address v-model="editData.address_code"></select-address>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-sm-2 col-form-label" for="address_detail">所在详细地址</label>
          <div class="col-sm-10">
            <input
              v-model="editData.address_detail"
              class="form-control form-control-ml"
              id="address_detail"
              placeholder="请输入所在详细地址"
              type="text"
            />
            <div class="invalid-feedback">请输入所在详细地址</div>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-sm-2 col-form-label">购置时间</label>
          <div class="col-sm-10">
            <el-date-picker
              v-model="editData.purchase_date"
              type="date"
              style="width: 360px"
              value-format="yyyy-MM-dd"
              placeholder="请选择购置时间"
            ></el-date-picker>
            <!--<input v-model="editData.purchase_date"-->
            <!--class="form-control form-control-ml"-->
            <!--id="purchase_date"-->
            <!--placeholder="请输入或选择购置时间"-->
            <!--type="date">-->
            <div class="invalid-feedback">请输入或选择购置时间</div>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-sm-2 col-form-label" for="assets_amount">数量</label>
          <div class="col-sm-10">
            <input
              v-model="editData.assets_amount"
              class="form-control form-control-ml"
              id="assets_amount"
              placeholder="请输入数量"
              type="number"
              min="0"
              step="0.01"
            />
            <div class="invalid-feedback">请输入数量</div>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-sm-2 col-form-label" for="assets_unit">单位</label>
          <div class="col-sm-10">
            <input
              v-model="editData.assets_unit"
              class="form-control form-control-ml"
              id="assets_unit"
              placeholder="请输入单位"
              type="text"
            />
            <div class="invalid-feedback">请输入单位</div>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-sm-2 col-form-label" for="assets_value">价值</label>
          <div class="col-sm-10">
            <div class="input-group">
              <input
                v-model="editData.assets_value"
                class="form-control form-control-ml"
                id="assets_value"
                placeholder="请输入价值"
                type="number"
                min="0"
                step="0.0001"
              />
              <div class="input-group-append">
                <span class="input-group-text">万元</span>
              </div>
            </div>
            <div class="invalid-feedback">请输入价值</div>
          </div>
        </div>

        <fieldset class="form-group">
          <div class="row">
            <legend class="col-form-label col-sm-2 pt-0">权属情况</legend>
            <div class="col-sm-10">
              <div
                v-for="(value, rKey, index) in enumOwnSit"
                class="form-check form-check-inline"
                :key="index"
              >
                <input
                  v-model="editData.own_sit"
                  class="form-check-input"
                  :id="`own_sit${index}`"
                  name="own_sit"
                  type="radio"
                  :value="rKey"
                />
                <label class="form-check-label" :for="`own_sit${index}`">{{ value }}</label>
              </div>
            </div>
          </div>
        </fieldset>

        <fieldset class="form-group">
          <div class="row">
            <legend class="col-form-label col-sm-2 pt-0">是否抵押</legend>
            <div class="col-sm-10">
              <div
                v-for="(value, rKey, index) in enumIsMortgage"
                class="form-check form-check-inline"
                :key="index"
              >
                <input
                  v-model="editData.is_mortgage"
                  class="form-check-input"
                  :id="`is_mortgage${index}`"
                  name="is_mortgage"
                  type="radio"
                  :value="rKey"
                />
                <label class="form-check-label" :for="`is_mortgage${index}`">{{ value }}</label>
              </div>
            </div>
          </div>
        </fieldset>

        <div class="form-group row">
          <label class="col-sm-2 col-form-label" for="assets_term">使用期限</label>
          <div class="col-sm-10">
            <div class="input-group">
              <input
                v-model="editData.assets_term"
                class="form-control form-control-ml"
                id="assets_term"
                placeholder="请输入使用期限"
                type="number"
                min="0"
                step="1"
                @input="onAssetsTermInput"
              />
              <div class="input-group-append">
                <span class="input-group-text">年</span>
              </div>
              <el-checkbox v-model="assetsTermCheck" class="ml-3 mt-2" @change="onAssetsTermChange">
                {{ assetsTermLabel }}
              </el-checkbox>
            </div>
            <div class="invalid-feedback">请输入使用期限</div>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-sm-2 col-form-label" for="remark">备注</label>
          <div class="col-sm-10">
            <input
              v-model="editData.remark"
              class="form-control form-control-ml"
              id="remark"
              placeholder="请输入备注"
              type="text"
            />
            <div class="invalid-feedback">请输入备注</div>
          </div>
        </div>
      </form>

      <div class="row mt-5">
        <div class="col-sm-10 offset-sm-2">
          <el-button class="btn-long" type="primary" :loading="saveLoading" @click="onSubmit">
            保存
          </el-button>
        </div>
      </div>
    </el-dialog>

    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入资产信息"
      :post-api="postUrl"
      excel-template="/static/files/资产信息导入模板.xlsx"
      @success="handleImportSucess"
    ></import-excel>
  </div>
</template>
<script>
// import FormComponent from '@/components/FormComponent'
import selectAddress from '@/components/select/SelectAddress'
import { enumAssetsType, enumIsMortgage, enumOwnSit } from '@/credit/plugins/enum'
import ImportExcel from '@/components/ImportExcel'
export default {
  components: {
    // FormComponent
    selectAddress,
    ImportExcel,
  },
  props: {},
  data() {
    return {
      dialogImportVisible: false,
      postUrl: '',
      enumAssetsType,
      enumOwnSit,
      enumIsMortgage,

      // 由于使用期限需要加“长期”，类型无法用FormComponent统一来处理，只有自已写表单
      relatedId: '',
      saveLoading: false,
      totalCount: 0,
      tableData: [],
      editVisible: false,
      wasValidated: false,
      tableName: 'datum_customer_assets',
      tableId: '',
      editData: {
        assets_belong_type: 2, // 默认企业
        assets_name: '',
        assets_type: 1,
        address_code: '',
        address_detail: '',
        purchase_date: '',
        assets_amount: '',
        assets_unit: '',
        assets_value: '',
        own_sit: 2,
        is_mortgage: 0,
        assets_term: '',
        remark: '',
      },
      editDataInit: {},
      filterKeys: ['purchase_date', 'assets_amount', 'assets_value'],

      // 使用期限添加 “长期选项”
      lastAssetsTerm: '',
      assetsTermCheck: false,
      assetsTermLabel: '长期',
      params: {
        index: 1,
        size: 10,
        address_code: '',
        customer_name: '',
        product_name: '',
        'service_id.eq': '',
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.editDataInit = { ...this.editData }
    this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view'))
    this.relatedId = this.$route.query.id || sessionStorage.getItem('customer_related_id')
    this.postUrl =
      '/api/credit/import/?importKey=datum_customer_assets_template&where=' +
      encodeURIComponent(
        '"datum_customer_assets.service_id".eq(' + this.$store.getters.org.clientId + ')'
      ) +
      encodeURIComponent('&"datum_customer_assets.customer_related_id".eq(relatedId)')

    this.getData()
  },
  mounted() {},
  methods: {
    getData() {
      this.params['assets_belong_type.eq'] = '2'
      this.params['service_id.eq'] = this.$store.getters.org.clientId
      this.$api
        .getData('credit', this.tableName, this.params, {
          create_time: 'desc',
        })
        .then(res => {
          this.tableData = (res && res.data && res.data.data) || []
          this.totalCount = (res && res.data && res.data.totalCount) || 0
        })
    },

    edit(p) {
      this.editVisible = true
      if (p) {
        Object.keys(this.editData).forEach(key => {
          this.editData[key] = p[key] || ''
        })
        this.tableId = p.id

        // “长期”处理
        if (this.editData.assets_term === this.assetsTermLabel) {
          this.editData.assets_term = ''
          this.assetsTermCheck = true
        }
      }
    },

    beforeClose() {
      this.wasValidated = false
      this.tableId = ''
      this.editData = { ...this.editDataInit }
      this.lastAssetsTerm = ''
      this.assetsTermCheck = false
      this.editVisible = false
    },

    onSubmit() {
      this.wasValidated = true
      const form = this.$refs.form
      if (!form.checkValidity()) {
        return this.$message.error('输入错误，请检查您的输入！')
      }

      // 构建formData，过滤掉number,date中为空的字段
      const formData = {}
      Object.keys(this.editData).forEach(key => {
        if (this.filterKeys.indexOf(key) > -1) {
          if (this.editData[key]) {
            formData[key] = this.editData[key]
          }
        } else {
          formData[key] = this.editData[key]
        }
      })

      // “长期”处理
      if (this.assetsTermCheck) {
        formData.assets_term = this.assetsTermLabel
      }

      if (this.tableId) {
        this.putData(formData)
      } else {
        formData.customer_related_id = this.relatedId
        formData.customer_id = this.customerData.customer_id
        formData.customer_name = this.customerData.customer_name
        formData.datum_customer_shareholder_id = this.customerData.customer_id
        this.postData(formData)
      }
    },
    async eventuate(row) {
      row.customer_related_id = 'relatedIdUpdate'
      let [res, err] = await this.$utils.promise(
        this.$api.updateData('credit', 'datum_customer_assets', row.id, row)
      )
      if (res) {
        this.$message.success('归集成功！')
        this.getLevelReview()
      } else {
        this.$message.error(`归集失败，请重试！（${err.status}）`)
      }
    },
    // 导入
    handleImportSucess() {
      this.getData()
      this.dialogImportVisible = false
    },
    async putData(formData) {
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.updateData('credit', this.tableName, this.tableId, formData)
      )
      this.saveLoading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.beforeClose()
        this.getData()
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },

    async postData(formData) {
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addData('credit', this.tableName, formData)
      )
      this.saveLoading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.beforeClose()
        this.getData()
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },

    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData('credit', this.tableName, item.id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },

    onAssetsTermInput() {
      this.assetsTermCheck = false
    },

    onAssetsTermChange(val) {
      if (val) {
        this.lastAssetsTerm = this.editData.assets_term
        this.editData.assets_term = ''
      } else {
        this.editData.assets_term = this.lastAssetsTerm
      }
    },
  },
}
</script>
<style scoped></style>
